package com.example.game;


import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;


import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;




public class GamePage extends AppCompatActivity implements View.OnClickListener {
    private static final int COMPLETED = 0;
    String databaseTAG = "databaseTag";
    String debugTag = "debugTag";
    static Timer timer = new Timer();
//    static boolean schedule_is_running = false;

    String str_display = "";
    static public Player player = new Player();
    static public DatabaseHelper databaseHelper = new DatabaseHelper();
    Button GamePageButton, ToolPageButton, BuildingPageButton;
    private setBuildingFragment BuildingFragment;
    private setToolFragment ToolFragment;
    private setGameFragment GameFragment;


    public FragmentManager fm = getFragmentManager();


    static boolean back_from_video_page = false; //修复从video_page返回时会触发多次timer.schedule的bug


    Handler handler_refresh = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == COMPLETED) {
                double point_production = player.production - (int) player.production;   //得到production的小数部分
                player.point += point_production / 0.05;
                if (player.point >= 20) {
                    player.cash += 1;
                    player.point -= 20;
                    Log.d("timer timer TAG", "run: just running");
                }
                //   Log.d("pointTAG", "run: " + String.valueOf(player.point));
                player.cash += player.production;


                TextView display_cash_textview = (TextView) findViewById(R.id.Game_Cash);
                TextView display_production_textview = (TextView) findViewById(R.id.Game_Production);
                //too noisy
                //Log.d(debugTag, "timeTag: checkpoint");
                str_display = player.convertLongToString(player.cash);
                display_cash_textview.setText(str_display);
                str_display = player.convertLongToString((long) (player.production * 20));     //production*20肯定是一个整数
                str_display = str_display + "个/秒";
                display_production_textview.setText(str_display);
            }
        }
    };


//    public void setDataPath() {
//        player.DATA_PATH = getFilesDir().getPath() + "data/" + getPackageName() + "/databases";
//    }

    //重写了点击返回键时的方法，这里会先保存，再用intent打开MainActivity
    //为了防止返回键导致的混乱，我重写了所有页面的onKeyDown方法
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //点击返回键调用方法
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            databaseHelper.saveGame();
            finish();
            Intent intent = new Intent();
            intent.setClass(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            timerTask_refresh.cancel();
            startActivity(intent);

        }
        return false;
    }


    public void Init_Saved_Game() {

        //下面是SQLite相关部分
        SQLiteDatabase db = databaseHelper.getDataBase();

        databaseHelper.make_save_file();


        String sql_cmd = "";
        Log.d(databaseTAG, "onCreatedatabase: checkpoint 5 :table checked");
        int count = databaseHelper.getDatabaseCount(db);
        if (count != 0) {
            databaseHelper.loadGame();
            //读取存档
        } else {
            Log.d(databaseTAG, "record not existed, creating new record");      //表中没有记录，新建一条记录（开始新游戏）

            sql_cmd = "insert into user values(?";
            for (int i = 0; i < player.BUILDING_TYPE_COUNT; i++) {
                sql_cmd = sql_cmd + ",?";
            }
            sql_cmd = sql_cmd + ")";
            Log.d(databaseTAG, "Creating new record : SQL_CMD = " + sql_cmd);
            int[] empty_array_list = new int[21];    //新存档为全0
            player.new_record();
            db.execSQL(sql_cmd, new Object[]{empty_array_list});
            //新建游戏存档
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        String s = "onCreate";

        Log.d(s, "onCreate: 第一个");
        super.onCreate(savedInstanceState);
        Log.d(s, "onCreate: 第二个");
        setContentView(R.layout.game_page_layout);
        Log.d(s, "onCreate: 第三个");
        Button button_click = (Button) findViewById(R.id.button_click);       //点击获得一个单位cash

        Log.d(s, "onCreate: 第四个");
//        Button button_save = (Button) findViewById(R.id.Game_Save_Button);
        Log.d(s, "onCreate: 第五个");

        //调用函数，从数据库中读取保存的游戏
//        setDataPath();
        Init_Saved_Game();


        Log.d(s, "onCreate: 第六个");
//        button_save.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                databaseHelper.saveGame();
//                //保存游戏进度
//                Log.d(databaseTAG, "onSave: checkpoint 3 :insert contaxt");
//            }
//        });

        Log.d(s, "onCreate: 第八个");
        // 初始化控件和声明事件
        GamePageButton = (Button) findViewById(R.id.Game_Page_Button);
        ToolPageButton = (Button) findViewById(R.id.Tools_Page_Button);
        BuildingPageButton = (Button) findViewById(R.id.Building_Page_Button);
        Typeface typeface = Typeface.createFromAsset(getAssets(), "MFYiCha_Noncommercial-Regular.ttf");
        GamePageButton.setTypeface(typeface);
        ToolPageButton.setTypeface(typeface);
        BuildingPageButton.setTypeface(typeface);
        GamePageButton.setOnClickListener(this);
        ToolPageButton.setOnClickListener(this);
        BuildingPageButton.setOnClickListener(this);
        //调用设置默认fragment的函数
        setDefaultFragment();

        timer.schedule(timerTask_refresh, 0, 50);
        String TAG = "TAG_find_listview";
        Log.d(TAG, "onCreate: step1");

    }

    //这个函数的作用是使用默认的Fragment（即GamePage）来填充
    private void setDefaultFragment() {
        String s = "setdefaultFragment";
        Log.d(s, "setDefaultFragment: ");
        android.app.FragmentTransaction transaction = fm.beginTransaction();
        GameFragment = new setGameFragment();
        transaction.replace(R.id.Fragment, GameFragment);
        transaction.commit();
        Log.d(s, "onClick: 默认fragment装好了");

    }

    @SuppressLint("WrongConstant")
    @Override
    public void onClick(View v) {
        String s = "onClick";
        FragmentManager fm = getFragmentManager();
        // 开启Fragment事务
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        Log.d(s, "onClick: 事务完成");
        switch (v.getId()) {
            case R.id.Game_Page_Button:
                if (GameFragment == null) {
                    GameFragment = new setGameFragment();
                }
                Log.d(s, "onClick: 选了game");
                // 使用当前Fragment的布局替代id_content的控件
                transaction.replace(R.id.Fragment, GameFragment);
                break;
            case R.id.Tools_Page_Button:
                if (ToolFragment == null) {
                    ToolFragment = new setToolFragment();
                }
                Log.d(s, "onClick: 选了tool");
                transaction.replace(R.id.Fragment, ToolFragment);
                break;
            case R.id.Building_Page_Button:
                if (BuildingFragment == null) {
                    BuildingFragment = new setBuildingFragment();
                }
                Log.d(s, "onClick: 选了building");
                transaction.replace(R.id.Fragment, BuildingFragment);
                break;
        }
        // transaction.addToBackStack();
        // 事务提交
        transaction.commit();
    }


    /**
     * 以下的几个方法用来，让fragment能够监听touch事件
     */
    private ArrayList<MyOnTouchListener> onTouchListeners = new ArrayList<MyOnTouchListener>(
            10);

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        for (MyOnTouchListener listener : onTouchListeners) {
            listener.onTouch(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    public void registerMyOnTouchListener(MyOnTouchListener myOnTouchListener) {
        onTouchListeners.add(myOnTouchListener);
    }

    public void unregisterMyOnTouchListener(MyOnTouchListener myOnTouchListener) {
        onTouchListeners.remove(myOnTouchListener);
    }

    public interface MyOnTouchListener {
        public boolean onTouch(MotionEvent ev);
    }

    TimerTask timerTask_refresh = new TimerTask() {
        @Override
        public void run() {

            Message msg = new Message();
            msg.what = COMPLETED;
            handler_refresh.sendMessage(msg);


        }
    };

//    final TimerTask timerTask_refresh = new TimerTask() {
//        @Override
//        public void run() {
//            double point_production = player.production - (int)player.production;   //得到production的小数部分
//            player.point += point_production / 0.05;
//            if(player.point >= 20){
//                player.cash += 1;
//                player.point -= 20;
//                Log.d("timer timer TAG", "run: just running");
//            }
//            //   Log.d("pointTAG", "run: " + String.valueOf(player.point));
//            player.cash += player.production;
//            Message msg = new Message();
//            msg.what = COMPLETED;
//            handler_refresh.sendMessage(msg);
//
//                if(back_from_video_page){
//                    Log.d("timer tag", "run: cancel timerTask");
//                    timerTask_refresh.cancel();
//                }
//        }
//    };

    public void setTimerTask_state(TimerTask timerTask) {
        Field field;            //通过反射，设置TimerTask的state属性为0，以避免Task already scheduled or cancelled报错
        try {
            field = TimerTask.class.getDeclaredField("state");
            field.setAccessible(true);
            field.set(timerTask, 0);
            Log.d("setTimerTask_state_TAG", "set state finish");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String myTag = "这是在设置Tool里面的点击监听";
//        String text= listView.getItemAtPosition(position)+"";
//        Toast.makeText(getActivity(), "position="+position+"text="+text,
//                Toast.LENGTH_SHORT).show();
        if (position == 2) {
            databaseHelper.saveGame();
            Log.d(myTag, "onClick: checkpoint1");
            //点击了视频
            timerTask_refresh.cancel();
            Log.d(myTag, "onClick: checkpoint2");
        }
    }



}












